// 所有模块都通过 define 来定义
define(function(require, exports, module) {

	// 通过 require 引入依赖
	require('jquery');
	require('./css/upload.css');
	require('./src/default.css');
	require('./src/kindeditor-min.js');
	require.async('./src/lang/zh_CN.min.js');
	require('layer');
	
	/**
	 * config = {appid:'',appkey:''}
	 */
	exports.run = function(config){
		var uploadurl = '/material/file/upload/appid/'+config.appid+'/appkey/'+config.appkey;
		var editor = KindEditor.editor({
			uploadJson : uploadurl,
			allowFileManager : false,
			afterUpload : function(url,data,name) {
				if (data.error === 0) {
					//currentFileId = data.file_id;
					var div = $("#all-files");
					var html = '<li id="file_li_'+data.file_id+'">'+
								'<span style="float:left;margin-right:10px;">'+data.file_name+'</span><a href="'+data.file_path+'" target="_blank" style="float:left;">下载</a> <a href="javascript:;" data-id="'+data.file_id+'" style="float:right" class="delfile">删除</a>'+ 
								'<input type="hidden" name="file_list_id[]" value="'+data.file_id+'" />'+
								'<div style="clear:both"></div>'+
							'</li>';
					div.append(html);
					
					doing(config); //新dom注入点击事件
				} else {
					alert(data.msg);
				}
			}
		});

		//点击打开上传文件窗口
		$('#uploadButton_s').click(function() {

			editor.loadPlugin('insertfile', function() {
				editor.plugin.fileDialog({
					clickFn : function(url, title) {
						editor.hideDialog();
					}
				});
			});

		});


		function doing(config){
			$('.delfile').click(function(){
				var fileid = $(this).attr('data-id');
				var asker = layer.confirm('是否确定删除?', function(){
					divid = "#file_li_"+fileid;
					var delurl = '/material/file/del/appid/'+config.appid+'/appkey/'+config.appkey;
					$.get(delurl+'/ids/'+fileid,function(data){
						if(data['status'] == 1){
							$(divid).remove();
						}else{
							alert('图片无法删除');
						}
					},'json');
	
					layer.close(asker);
				});
			});
		}
		
		doing();
		

	}
	

});